﻿using RabbitMQ.Gateway;
using RabbitMQ.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RabbitMQDemo
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        public T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sJson"></param>
        /// <returns></returns>
        public static string Serialize(object obj)
        {
            string sJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj);
            return sJson;
        }

        /// <summary>
        /// json 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sJson"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string sJson) where T : class
        {
            T obj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<T>(sJson);
            return obj;
        }

        public static string test(string message, MessageObj _objM)
        {
            string _collectionName = _objM.CollectionName;
            string _type = _objM.Type;
            int _operatetype = _objM.OperateType;

            string _typeStr = string.Format("\"Type\":\"{0}\"", _objM.Type);
            string _collectionNameStr = string.Format("\"CollectionName\":\"{0}\"", _objM.CollectionName);


            string _objectStr = message.Substring(1, message.Length - 2);
            _objectStr = _objectStr.Replace(_typeStr, "");
            _objectStr = _objectStr.Replace(_collectionNameStr, "");
            if (_objectStr.Substring(0, 1) == ",")
            {
                _objectStr = _objectStr.Substring(1, _objectStr.Length - 1);
            }
            if (_objectStr.Substring(0, 1) == ",")
            {
                _objectStr = _objectStr.Substring(1, _objectStr.Length - 1);
            }
            if (_objectStr.Substring(_objectStr.Length - 1, 1) == ",")
            {
                _objectStr = _objectStr.Substring(0, _objectStr.Length - 1);
            }
            if (_objectStr.Substring(_objectStr.Length - 1, 1) == ",")
            {
                _objectStr = _objectStr.Substring(0, _objectStr.Length - 1);
            }
            _objectStr = _objectStr.Replace("\"Object\":", "");
            return _objectStr;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RQProducer.EfficientSend("aaa");
          
            while (true)
            {
                MessageObj obj = new MessageObj();
                obj.CollectionName = "myname1";
                obj.Type = "mytype";
                obj.OperateType = 0;
                obj.Object = new stu { name = "zcy", age = 12 };

                bool bl = RQProducer.EfficientSend(obj);
                
            }
       
        }

        private void button2_Click(object sender, EventArgs e)
        {
             
            RQConsumer.ConsumerStart();

        }

        private void button3_Click(object sender, EventArgs e)
        {
            RQConsumer.ConsumerReStart(false);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            MessageObj obj = new MessageObj();
            obj.CollectionName = "myname";
            obj.Type = "mytype";
            obj.OperateType = 0;
            obj.Object = new stu { name = "zcy", age = 12 };

            byte[] bt = ObjectToByte(obj);
            MessageObj msg = (MessageObj)ByteToObject(bt);
        }

        /// <summary>
        /// 对象转换成二进制流
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ObjectToByte(object obj)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bf.Serialize(stream, obj);
            byte[] bytes = stream.GetBuffer();
            stream.Close();
            return bytes;
        }

        /// <summary>
        /// 二进制流还原成对象
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static object ByteToObject(byte[] bytes)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
            System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Object reobj = bf.Deserialize(stream);
            stream.Close();
            return reobj;
        }

        Stopwatch watch = new Stopwatch();
      
        private void button5_Click(object sender, EventArgs e)
        {
            Dictionary<string, log4net.ILog> logw = new Dictionary<string, log4net.ILog>();

            log4net.ILog logee = log4net.LogManager.GetLogger("mqframeloger");
            logw.Add("aa", logee);

            logee = log4net.LogManager.GetLogger("parmloger");
            logw.Add("bb", logee);

            logw["aa"].Error("this from mqframeloger 3 ");
            logw["bb"].Error("this from parmloger 3");

            return;

            log4net.ILog loge = log4net.LogManager.GetLogger("mailloger");

            //loge.Info("this is a bug in loge.Error");
            //loge.Warn("this is a bug in loge.Warn");
            loge.Error("this is a bug in loge.Error");

            return;

          

           
            MessageObj obj = new MessageObj();
            obj.CollectionName = "myname";
            obj.Type = "mytype";
            obj.OperateType = 0;
            obj.Object = new { name = "zcy", age = 12 };

            string str = Serialize(obj);
            string str2 = JsonUtils.ToJSON(obj);
            return;

            log4net.ILog log = log4net.LogManager.GetLogger(typeof(Form3));
            log.Error("this is a test 2");
            RabbitMQ.Gateway.Log.loger.Error("xx");
            
            return;


            //MailSender.Send("消息同步服务启动异常", "there hava a error");

            watch.Reset();
            watch.Start();

            System.Threading.Thread.Sleep(1000);

            watch.Stop();

            string ss = CheckNormalTs(watch);
        }

        protected string CheckNormalTs(Stopwatch watch)
        {
            watch.Stop();
            string s = string.Empty;
            if (watch.ElapsedMilliseconds <= 1500)
            {
                s = "正 常";
            }
            else if (watch.ElapsedMilliseconds <= 3000)
            {
                s = "基本正常";
            }
            else if (watch.ElapsedMilliseconds <= 5000)
            {
                s = "不太正常";
            }
            else if (watch.ElapsedMilliseconds <= 15000)
            {
                s = "不 正常";
            }
            else if (watch.ElapsedMilliseconds <= 30000)
            {
                s = "很不正常";
            }
            else if (watch.ElapsedMilliseconds <= 60000)
            {
                s = "极不正常";
            }
            else
            {
                s = "见鬼了";
            }

            s = string.Format("{0} 处理时间：{1}（毫秒）", s, watch.ElapsedMilliseconds);
            return s;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            new GatewayFactory().InitMQInfo();
        }

        private void button7_Click(object sender, EventArgs e)
        {

        }
    }

    [Serializable]
    public class stu
    {
       public string name { get; set; }
       public int age { get; set; }
    }

    public class Msg
    {
        /// <summary>
        /// 对象类型
        /// </summary>
        public string Type { get; set; }
        /// <summary>
        /// 对象实例
        /// </summary>
        public Object Object { get; set; }
        /// <summary>
        /// 的集合名
        /// </summary>
        public string CollectionName { get; set; }
        /// <summary>
        /// 操作类型
        /// </summary>
        public int OperateType { get; set; }
    }
}
